package timbap.visualizer.api.plugin.container;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import timbap.visualizer.api.plugin.Plugin;

/**
 * The <code>AbstractPluginSwitch</code> provides a common base
 * implementation of the <code>PluginSwitch</code> interface
 * that should be used by all timbap plugins that switch between
 * various other timbap plugins.
 *
 * @author  Andreas Pabst
 * @see     timbap.visualizer.api.plugin.container.PluginSwitch
 * @see     timbap.visualizer.api.plugin.container.AbstractPluginContainer
 */
public class AbstractPluginSwitch extends AbstractPluginContainer implements PluginSwitch {

	private static final Log LOG = LogFactory.getLog(AbstractPluginSwitch.class);
    public static final int ERROR_HANDLING_INDEX = 0;
    
    private int activePluginIndex = -1;
    
	public void draw() {
		getActivePlugin().draw();
	}

    public void activatePlugin(Plugin pPlugin) {
    	pPlugin.activate();
    }
    
    public Plugin getActivePlugin() {
    	Plugin tActivePlugin = null;
        if (getPlugins().size() > activePluginIndex && activePluginIndex >= 0) {
            tActivePlugin = getPlugins().get(activePluginIndex);
        }
        return tActivePlugin;
    }
    
    public void toFirst() {
    	to(0);
    }
    
    public void toNext() {
    	int tNewPluginIndex =(activePluginIndex + 1) % getPlugins().size();
    	to(tNewPluginIndex);
	}
    
    public void toPrevious() {
    	int tNewPluginIndex = (activePluginIndex - 1 + getPlugins().size()) % getPlugins().size();
        to(tNewPluginIndex);
	}
    
    public void toError() {
    	to(ERROR_HANDLING_INDEX);
	}

    protected final void to(int pPluginIndex) {
    	int tFormerPluginIndex = activePluginIndex;
        
    	if (pPluginIndex != tFormerPluginIndex) {
    		
    		String tFormerPlugin;
    		if (tFormerPluginIndex > 0 && tFormerPluginIndex < getPlugins().size()) {
    			tFormerPlugin = getPlugins().get(tFormerPluginIndex).toString();
    		} else {
    			tFormerPlugin = "none";
    		}
	    	LOG.info("Changing plugin from " 
	                + tFormerPlugin
	                + " to " + getPlugins().get(pPluginIndex).toString());
	    	activePluginIndex = pPluginIndex;
	        activatePlugin(getActivePlugin());
    	}
    }

	@Override
    public void activate() {
        super.activate();
        toFirst();
        if (LOG.isDebugEnabled()) {
            LOG.debug("First plugin " + getActivePlugin() + " of plugin fork " + this + " activated.");
        }
    }

	
    
}
